import React, { Fragment, useEffect, useState } from 'react'
import { Avatar, Button, Col, List, message, Row, Space, Typography } from 'antd'
import { Divider } from 'antd';
import Title from "antd/es/skeleton/Title";
import Paragraph from "antd/es/skeleton/Paragraph";
import TextArea from "antd/es/input/TextArea";
import { parseHTMLToReact } from "../views/blog";
import { getArticle, getArticleCommentList, updateArticle } from "../api/article";
import {
    CommentOutlined, EyeOutlined, FieldTimeOutlined,
    FileOutlined,
    LikeOutlined,
    UserOutlined
} from "@ant-design/icons";
import { addComments, getComments, updateComments } from "../api/comment";
import './css/content.css'

export function Content ({ BlogInfo }) {
    const { Title, Paragraph, Text, Link } = Typography;
    // 获取该文章的基本信息
    const {
        articleId,
        articleTitle,
        articleContent,
        articleAuthor,
        articleDate,
        articlePicpath,
        articleViews,
        articleLikes
    } = BlogInfo;
    // 弹窗api
    const [messageApi, contextHolder] = message.useMessage();
    const info = (message, type) => {
        messageApi.open({
            type: type,
            content: message,
        });
    };

    // 1.点赞功能
    const [likes, setLikes] = useState(0) // 使用状态代替请求结果 用户点击点赞后不必立刻刷新影响体验
    const [loadings, setLoadings] = useState([])


    // 获取文章的基本信息
    useEffect(() => {
        if (articleId !== undefined) {
            getArticle(articleId).then(res => {
                console.log('文章信息', res)
                setLikes(res.data.data.articleLikes)
            })
        }
    }, [articleId]);

    const enterLoading = (index) => {
        setLoadings((prevLoadings) => {
            const newLoadings = [...prevLoadings];
            newLoadings[index] = true;
            return newLoadings;
        });
        setTimeout(() => {
            setLoadings((prevLoadings) => {
                const newLoadings = [...prevLoadings];
                newLoadings[index] = false;
                return newLoadings;
            });
        }, 1000);
    };
    // 文章点赞
    const addLikes = () => {
        // 获取文章信息 然后修改文章信息
        getArticle(articleId).then(res => {
            // 获取文章的点赞数
            const articleLikes = res.data.data.articleLikes;
            enterLoading(0)
            updateArticle({ ...res.data.data, articleLikes: articleLikes + 1 }).then(res => {
                setLikes(articleLikes + 1)
                info('点赞成功', 'success')
            }).catch(err => {
                info('点赞失败', 'error')
            })
        })
    }
    // 2.评论功能
    const [userComment, setUserComment] = useState('')
    const [borderStyle, setBorderStyle] = useState('')

    const changeComment = (e) => {
        setUserComment(e.target.value)
        if (e.target.value.length === e.target.maxLength) {
            setBorderStyle('#f32b2b');
        } else {
            setBorderStyle('')
        }
    }
    const addUserComments = () => {
        getArticle(articleId).then(res => {
            // 调用修改接口
            addComments({ targetArticleId: articleId, commentContent: userComment }).then(res => {
                info('评论成功', 'success')
                setTimeout(() => {
                    setUserComment('')
                    setCommentList([...commentList, {
                        commentPublisher: '你',
                        commentContent: userComment
                    }])
                }, 200)
            }).catch(err => {
                info('评论失败', 'error')
            })
        })
    }
    const IconsInfo = (icon, title, info) => {
        return (
            <span>
                {icon}{title}:<span className="icons-info">{info}</span>
            </span>
        )
    }
    const iconList = [
        {
            icon: <UserOutlined />,
            title: '作者',
            info: articleAuthor
        },
        {
            icon: <FieldTimeOutlined />,
            title: '发表于',
            info: articleDate
        },
        {
            icon: <EyeOutlined />,
            title: '观看数',
            info: articleViews
        },
        {
            icon: <LikeOutlined />,
            title: '点赞数',
            info: likes
        }
    ]
    // 获取该文章的评论列表
    const [commentList, setCommentList] = useState([])
    const [pageNum, setPageNum] = useState(1)
    const [pageSize, setPageSize] = useState(10)
    const [commentLikesLoading, setCommentLikesLoading] = useState(false)
    // todo 分页
    useEffect(() => {
        getArticleCommentList({ articleId: articleId, pageNum: pageNum, pageSize: pageSize })
            .then(res => {
                console.log(res)
                setCommentList(res.data.rows)
            })
    }, [articleId, pageNum]);

    // 评论点赞功能
    const addCommentLikes = (item) => {
        setCommentLikesLoading(true);
        // 先更新本地状态
        const updatedComment = { ...item, commentLikes: item.commentLikes + 1 };
        // 更新评论列表中的对应项
        setCommentList(prevList =>
            prevList.map(comment =>
                comment.commentId === item.commentId ? updatedComment : comment
            )
        );
        updateComments(updatedComment).then(res => {
            if (res.data.code === 200) {
                info('点赞成功', 'success');
            } else {
                info(res.data.msg, 'error');
            }
        }).catch(err => {
            info('点赞失败', 'error');
            // 如果失败，恢复原状态
            setCommentList(prevList =>
                prevList.map(comment =>
                    comment.commentId === item.commentId ? item : comment
                )
            );
        }).finally(() => {
            setCommentLikesLoading(false);
        });
    }
    return (
        <Fragment>
            {contextHolder}
            <Typography>
                <Title>{articleTitle}</Title>
                <Paragraph>
                    <blockquote>
                        <Space>
                            {iconList.map(item => {
                                return (IconsInfo(item.icon, item.title, item.info))
                            })}
                        </Space>
                        <Button style={{ float: 'right' }} type="primary" autoInsertSpace={false}
                            onClick={addLikes} loading={loadings[0]}>
                            点赞
                        </Button>
                    </blockquote>
                </Paragraph>
                <Divider />
                {/*文章内容*/}
                <Title level={3}><FileOutlined />内容</Title>
                <Paragraph>{parseHTMLToReact(articleContent)}</Paragraph>
                <Divider />
                <Title level={3}><CommentOutlined />评论区</Title>
                <Divider />
                {/*评论列表*/}
                <List
                    size="small"
                    pagination={{
                        onChange: (page) => {
                            setPageNum(page)
                        },
                        pageSize: 10,
                    }}
                    dataSource={commentList}
                    renderItem={(item) => (
                        <List.Item
                            key={item.title}>
                            <List.Item.Meta
                                title={<a href={item.commentPublisher}>{item.commentPublisher}:</a>}
                                description={item.commentContent}
                            />
                            <div>
                                点赞数:{item.commentLikes}
                                <Button type="primary" autoInsertSpace={false} style={{ marginLeft: '10px' }}
                                    onClick={() => addCommentLikes(item)} loading={commentLikesLoading}>
                                    点赞
                                </Button>
                            </div>
                        </List.Item>
                    )}
                />
                <Divider />
            </Typography>
            <Row justify={"center"} gutter={10} align={"middle"}>
                <Col span={2}>
                    <Avatar src={`https://api.dicebear.com/7.x/miniavs/svg?seed=${1}`} size={64} shape={"square"} />
                </Col>
                <Col span={12}>
                    <TextArea rows={4} placeholder="发表一条友善的评论,最多30字.." maxLength={50} value={userComment}
                        onChange={(e) => changeComment(e)}
                        style={{ border: `1px solid ${borderStyle || '#d9d9d9'}` }} />
                </Col>
                <Col span={6}>
                    <Row justify={"center"} gutter={10}>
                        <Col>
                            <Button type="primary" autoInsertSpace={false} onClick={addUserComments}>
                                评论
                            </Button>
                        </Col>
                    </Row>
                </Col>
            </Row>
        </Fragment>
    )
}



